//
//  FDOioData.m
//  foodash
//
//  Created by Kasper Kronborg on 11/02/09.
//  Copyright 2009 Xstream Media Solutions. All rights reserved.
//

#import "FDOioData.h"


@implementation FDOioData

- (NSMutableArray *)localCouncils:(int)region
{
	NSLog(@"Fetching from: %@", [NSString stringWithFormat:@"http://oiorest.dk/danmark/regioner/%d/kommuner", region]);
	NSXMLDocument * xmlDocument = [self xmlDocument:[NSString stringWithFormat:@"http://oiorest.dk/danmark/regioner/%d/kommuner", region]];
	NSLog(@"XML: %@", xmlDocument);
	NSError * error = [[NSError alloc] init];
	NSArray * xmlCouncils = [xmlDocument nodesForXPath:@"/kommuner/kommune" error:&error];
	NSMutableArray * councils = [[[NSMutableArray alloc] init] autorelease];
	for (NSXMLElement * xmlElement in xmlCouncils) {
		NSMutableDictionary * council = [[[NSMutableDictionary alloc] init] autorelease];
		NSArray * nrArray = [xmlElement nodesForXPath:@"nr/text()" error:&error];
		[council setObject:[[nrArray objectAtIndex:0] stringValue] forKey:@"nr"];
		NSArray * navnArray = [xmlElement nodesForXPath:@"navn/text()" error:&error];
		[council setObject:[[navnArray objectAtIndex:0] stringValue] forKey:@"navn"];
		[councils addObject:council];
	}
	[error release];
	NSLog(@"Councils: %@", councils);
	return councils;
}

- (NSMutableArray *)regions
{
	NSXMLDocument * xmlDocument = [self xmlDocument:@"http://oiorest.dk/danmark/regioner"];
	NSError * error = [[NSError alloc] init];
	NSArray * xmlRegions = [xmlDocument nodesForXPath:@"/regioner/region" error:&error];
	NSMutableArray * regions = [[[NSMutableArray alloc] init] autorelease];
	for (NSXMLElement * xmlElement in xmlRegions) {
		NSMutableDictionary * region = [[[NSMutableDictionary alloc] init] autorelease];
		NSArray * nrArray = [xmlElement nodesForXPath:@"nr/text()" error:&error];
		[region setObject:[[nrArray objectAtIndex:0] stringValue] forKey:@"nr"];
		NSArray * navnArray = [xmlElement nodesForXPath:@"navn/text()" error:&error];
		[region setObject:[[navnArray objectAtIndex:0] stringValue] forKey:@"navn"];
		[regions addObject:region];
	}
	[error release];
	NSLog(@"Regions: %@", regions);
	return regions;
}

- (NSXMLDocument *)xmlDocument:(NSString *)aUrl;
{	
	NSURL * url = [[NSURL alloc] initWithString:aUrl];
	NSError * error = [[NSError alloc] init];
	NSXMLDocument * xmlDocument = [[[NSXMLDocument alloc] initWithContentsOfURL:url 
																		options:NSXMLDocumentIncludeContentTypeDeclaration 
																		  error:&error] autorelease];
	//NSLog(@"Errors %@", error);
	[error release];
	[url release];
	return xmlDocument;
}

@end
